import React, { useState, useEffect } from "react";
import classNames from "classnames";
import "./index.scss";
import { AtAccordion } from "taro-ui";
import { reportList } from "./constants";
import { inject, observer } from "mobx-react";
import { CommonList } from "../../../components/common-list";
import { OuterMemberData } from "../../../components/outer-member-data";
import { StatisticalOfConfirm } from "../../../components/statistical-of-confirm";
import { LiquidEachrt } from "../../../components/liquid-echart";
import { TrendChart } from "../../../components/trend-chart";
import { Assignment } from "../../../components/assignment";
import { CircleRing } from "../../../components/circle-ring";
import { NoRecord } from "../../../components/no-record";
import NoDashBoard from "../../../assets/no-dashboard.png";

import {
  fetchDashboardSort,
  fetchDashboardData,
  fetchDashboardConfig,
} from "../../../../src/api/dashboard";
import { getCurrentInstance } from "@tarojs/taro";
import { RootStore } from "src/store/root-store";
import {
  IDashboardSort,
  DashboardType,
  IDashboardConfig,
  IOuterDateChart,
} from "src/interfaces";
import Taro from "@tarojs/taro";

interface Props {
  rootStore?: RootStore;
}
const Index = ({ rootStore }: Props) => {
  const { curChannelInfo } = rootStore as RootStore;
  const [spaceId, setSpaceId] = useState<string>("");
  const [loading, setLoading] = useState<boolean>(false);
  const [chartIds, setChartIds] = useState<IDashboardSort[]>([]);
  const [chartDatas, setChartDatas] = useState<DashboardType[]>([]);
  const [dashboardConfig, setDashboardConfig] = useState<IDashboardConfig[]>(
    []
  );
  const [isOpen, setIsOpen] = useState(false);
  const chartComponent = {
    outerDateChart: OuterMemberData,
    outerConfirmStatisticsChart: StatisticalOfConfirm,
    taskStatisticsChart: LiquidEachrt,
    taskTrendChart: TrendChart,
    taskFileStatisticsChart: CircleRing,
    taskMemberDistributionChart: Assignment,
    fileStatisticsChart: CircleRing,
    issueChart: LiquidEachrt,
  };
  const test = (data, type, index) => {
    let dom;
    switch (type) {
      case "outerDateChart":
        dom = (
          <OuterMemberData
            key={`outerDateChart${index}`}
            originData={data}
            type={type}
          />
        );
        break;
      case "outerConfirmStatisticsChart":
        dom = (
          <StatisticalOfConfirm
            key={`outerConfirmStatisticsChart${index}`}
            originData={data}
            type={type}
          />
        );
        break;
      case "taskStatisticsChart":
        dom = (
          <LiquidEachrt
            key={`taskStatisticsChart${index}`}
            originData={data}
            type={type}
          />
        );
        break;
      case "taskTrendChart":
        dom = (
          <TrendChart
            key={`taskTrendChart${index}`}
            originData={data}
            type={type}
          />
        );
        break;
      case "taskFileStatisticsChart":
        dom = (
          <CircleRing
            key={`taskFileStatisticsChart${index}`}
            originData={data}
            type={type}
          />
        );
        break;
      case "taskMemberDistributionChart":
        dom = (
          <Assignment
            key={`taskMemberDistributionChart${index}`}
            originData={data}
            type={type}
          />
        );
        break;
      case "fileStatisticsChart":
        dom = (
          <CircleRing
            key={`fileStatisticsChart${index}`}
            originData={data}
            type={type}
          />
        );
        break;
      case "issueChart":
        dom = (
          <LiquidEachrt
            key={`issueChart${index}`}
            originData={data}
            type={type}
          />
        );
        break;
      default:
        null;
    }
    return dom;
  };
  useEffect(() => {
    const { router } = getCurrentInstance();
    const spaceId = router?.params?.spaceId || "";
    if (!spaceId) {
      alert("没有空间id");
      return;
    }
    setSpaceId(spaceId);
    const init = async () => {
      setLoading(true);
      Taro.showLoading();
      const [getDashboardSortRes, getDashboardConfigRes] = await Promise.all([
        fetchDashboardSort(spaceId, curChannelInfo?.id),
        fetchDashboardConfig(spaceId, curChannelInfo?.id),
      ]);
      if (getDashboardConfigRes?.code === 0) {
        const channelData = getDashboardConfigRes?.data.filter(
          (item: IDashboardConfig) => {
            return item?.isOuter && item?.isVisible && item?.selected;
          }
        );
        setDashboardConfig(channelData);
      }
      // 仪表盘报表顺序id
      if (getDashboardSortRes?.code === 0) {
        setChartIds(getDashboardSortRes?.data);
        const allPromise = getDashboardSortRes?.data?.map(async (item) => {
          const data = await fetchDashboardData(
            spaceId,
            curChannelInfo?.id,
            item?.id,
            {}
          );
          return data.data;
        });
        const chartData = await Promise.all(allPromise);
        Taro.hideLoading();
        setLoading(false);
        setChartDatas(chartData);
      } else {
        alert(getDashboardSortRes?.message);
      }
    };
    init();
  }, []);
  if (loading) return null;
  return (
    <div
      className={classNames("charts", {
        fix: isOpen,
      })}
    >
      {chartIds?.length > 0 ? (
        <div>
          <div className="chart-info">
            <span className="report-number">共{chartIds?.length}个报表</span>
            <p
              className="chart-channel"
              onClick={() => {
                setIsOpen(!isOpen);
              }}
            >
              {dashboardConfig?.length}个频道{" "}
              <span
                className={classNames("iconfont icon-down-line", {
                  rotate: isOpen,
                })}
              ></span>
            </p>

            <div
              className={classNames("chart-channel-container", {
                open: isOpen,
              })}
              onClick={() => {
                setIsOpen(false);
              }}
            >
              <CommonList
                setIsOpened={setIsOpen}
                setCurIndex={() => {}}
                curIndex={-1}
                list={dashboardConfig}
              />
            </div>
          </div>
          <div className="chart-container">
            {chartIds?.map((item, index) => {
              const type = item.type;
              return (
                chartDatas?.[index] && test(chartDatas?.[index], type, index)
              );
            })}
          </div>
        </div>
      ) : (
        <NoRecord img={NoDashBoard} text="暂无报表" />
      )}
    </div>
  );
};
export const Charts = observer(inject("rootStore")(Index));
